package com.zdsoft.p2p.user.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ConfigurableWebApplicationContext;

import com.zdsoft.p2p.user.domain.User;
import com.zdsoft.p2p.user.service.UserService;
import com.zdsoft.rock.common.controller.AbstractController;
import com.zdsoft.rock.common.model.domain.ResponseMsg;
import com.zdsoft.rock.common.pagination.PageRequest;
import com.zdsoft.rock.common.util.StringUtil;

@Controller
@RequestMapping("/user")
public class UserController extends AbstractController{

	@Resource 
	private ConfigurableWebApplicationContext wac;
	
	@RequestMapping("/index.do")
	public String index(){
		return "user/index";
	}
	
	@RequestMapping("/update.do")
	@ResponseBody
	public String update(){
		logger.debug("更新spring的上下文");
		wac.refresh();
		return "更新成功";
	}
	
	@RequestMapping("/user.do")
	public String user(){
		logger.debug("进入用户页面");
		return "user/user";
	}
	@Autowired
	private UserService userService;
	
	@RequestMapping("/list.do")
	public String list(User user,PageRequest pageRequest,ModelMap model){
		logger.debug("进入列表页面");
		model.put("pager", userService.findPager(user, pageRequest));
		return "user/list";
	}
	@RequestMapping("/edit.do")
	public String edit(String id,ModelMap model){
		logger.debug("进入编辑或新增界面:id={}",id);
		if(StringUtil.isEmpty(id)){
			model.put("user", new User());
		}else{
			model.put("user", userService.findById(id));
		}
		return "user/edit";
	}
	/**
	 * 保存用户信息，并跳转到列表页
	 * @param user
	 * @return
	 */
	@RequestMapping("/save.do")
	@ResponseBody
	public ResponseMsg<String> save(@Valid User user,BindingResult result){
		ResponseMsg<String> msg=new ResponseMsg<String>();
		logger.debug("保存指定的对象:{}",user);
		if(result.hasErrors()){
			List<ObjectError> errors=result.getAllErrors();
			for (ObjectError oe : errors) {
				logger.debug("校验错误:{}={}",oe.getObjectName(),oe.getDefaultMessage());
				msg.setMsg(String.format("%s=%s", oe.getObjectName(),oe.getDefaultMessage()));
			}
		}else{
			logger.debug("保存用户:{}",user);
			msg.setMsg("保存成功");
			userService.save(user);
		}
		return msg;
	}
}
